<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <title>代理模式</title>
    <style lang="css">
        .preload{
            display: block;
            width:160px;
            height: 160px;
        }
    </style>
</head>

<body>
    <h2>虚拟代理实现图片预加载</h2>
    <h3>将浏览器网速调整为50ms慢速才可以看到效果哟</h3>
    <h3>如果未来网速超快，不再需要预加载了，直接调用loadImage.setSrc()即可，代理方法与此方法保持了一致的函数名</h3>
    <h3>这里符合单一职责原则，同时符合开放-封闭原则</h3>
    <script type="text/javascript">
        var loadImage = (function(){
            var imgNode = document.createElement('img')
            imgNode.class= 'preload'
            document.body.appendChild(imgNode)
            return {
                setSrc:function(src){
                    imgNode.src = src
                }
            }
        })()
        var proxySetImg = (function(){
            var image = new Image()
            image.onload = function(){
                loadImage.setSrc(this.src)
            }
            return {
                setSrc: function (src) {
                    loadImage.setSrc('img/loading.gif')
                    image.src = src
                }

            }
        })()
        // loadImage.setSrc('img/loading.gif')

        proxySetImg.setSrc('https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1515480232&di=ddc8e182ef41c77f88718dc9ac11fb71&src=http://c.hiphotos.baidu.com/zhidao/pic/item/d6ca7bcb0a46f21f247ac1f4f6246b600d33aecf.jpg')


    </script>

</body>

</html>